# -*- coding: utf-8 -*-
'''
Created on 2012-9-6


@author: Administrator
'''

import datetime
from logic.login_session_mgr import LoginSessionMgr
import json

from core.db.companyx.shop import Shop
from core.db.companyx.shop_group import ShopGroup
from core.db.companyx.user import User
from core.db.companyx.user_right import UserRight
from sqlalchemy.orm import class_mapper
from core.util.debug import Log
from webob import Request, Response
from service.server_config import SrvConfig

def application(environ, start_response):
    '''
        entrance of apache wsgi application
    '''    
    req = Request(environ)
    res = Response()
    
    CompanyService.process(req, res)
    
    return res(environ, start_response)


class CompanyService(object):
    __setup__ = False
    log = None    
    
    @staticmethod
    def process(req, res):
        if CompanyService.__setup__ == False:
            Log.setPath(SrvConfig.getLogPath())
            CompanyService.log = Log()            
            CompanyService.__setup__ = True        
               
        try:
            dbsession = SrvConfig.getDefaultDBSession() 
            company_id = req.params["company_id"]
            username = req.params["username"]
            token = req.params["token"]
            #检查 TOKEN 的有效性
            if LoginSessionMgr.isSessionValid(company_id, username, token, dbsession) is False:
                res.json = {'ret':107, 'msg':'token is invalid'}
                CompanyService.log.e("CompanyService:process, token is invalid")
                return
            
            companySrv = CompanyService(dbsession)
            
            if req.params['mthod'] == 'get':
                return companySrv.getCompanyInfo(req, res)
            elif req.params['mthod'] == 'set':
                return companySrv.setCompanyInfo(req, res)
            else:
                res.json = {'ret':-1, 'msg':'unknown method %s' % req.params['method']}                
        except Exception,e:
            res.json = {'ret':-1, 'msg':'exception'}
            CompanyService.log.e('CompanyService:process, exception %s' % e)
        finally:
            dbsession.close()
             
    def __init__(self, dbsession):
        self.dbsession = dbsession
        

    def getCompanyInfo(self, req, res):
        '''
            公司X库保存的信息表      
        '''            
        config_table = req.params['type']
        
        CompanyService.log.d("tablename:%s" % config_table)
        config_table_classes = {}         
        config_table_classes["shop_group"] = ShopGroup
        config_table_classes["shop"] = Shop 
        config_table_classes["user_right"] = UserRight 
        config_table_classes["user"] = User 

        config_orderby = {}
        config_orderby["shop_group"] ="id"
        config_orderby["shop"] = "id asc,group_id asc "
        config_orderby["user_right"] = "user_id asc,id asc "
        config_orderby["user"] = "shop_id asc,id asc "
        
        if config_table in config_table_classes:
            table_class = config_table_classes[config_table]
            orderby = config_orderby[config_table]
            return self._getCompanyInfoByTable(req, res, table_class, orderby)
        else:            
            res.json = {'ret':-1, 'msg':'unknown configure'}
            CompanyService.log.e("CompanyService:getCompanyInfo, unknown configure")
        

    def _getCompanyInfoByTable(self, req, res, table_class, orderby):
        '''
            对读配置的响应
            table_class 要操作的表对应的ORM类
        '''
        try:
            #过滤出要更新的表字段名和字段值
            company_id = req.params['company_id']  
            table_class.doMapping(company_id)                      
            #获取记录操作
            query_result = self.dbsession.query(table_class).filter().order_by(orderby).all()            
            table_fields = {}                       
            for col in (class_mapper(table_class).mapped_table.c):
                table_fields[col.name]=col.name
                                                                                           
            CompanyService.log.d('CompanyService:_getCompanyInfoByTable:%s' % repr(table_fields))
                                
            returnlist = []                
            dicmy = {}
            dicmy["ret"] = 0
            dicmy["msg"] = 'success'
            icount = 0                     
            for r in query_result:
                icount = 1
                dicmyFF = {} 
                for field in  table_fields:
                    temp = getattr(r, table_fields[field])                  
                    if type(temp) is datetime.datetime:
                        dicmyFF[field] = str(temp)                        
                    else:
                        dicmyFF[field] = temp
                
                strtemp = json.dumps(dicmyFF)                
                returnlist.append(strtemp)
                                
            if icount == 0:
                res.json = {'ret':6, 'msg':'record is empty'}
                CompanyService.log.e('CompanyService:_getCompanyInfoByTable, record is empty')
                return
                               
            dicmy['data']=returnlist            
            res.json= dicmy
        except Exception, e:           
            CompanyService.log.e('CompanyService._getCompanyInfoByTable(): exception:%s' % e)
            res.json = {'ret':-1, 'msg':'exception'}
                
        
    def setCompanyInfo(self, req, res):
        '''
             修改  添加  删除  相关的信息 
        '''                
        config_table = req.params['config_table']
        
        config_table_classes = {}
        config_table_classes["shop_group"] = ShopGroup
        config_table_classes["shop"] = Shop
        config_table_classes["user_right"] = UserRight
        config_table_classes["user"] =  User
        
        if config_table in config_table_classes:
            table_class = config_table_classes[config_table]
            return self._setCompanyInfoByTable(req, res, table_class)
        else:
            res.json = {'ret':-1, 'msg':'unknown configure'}
            CompanyService.log.e("CompanyService:setCompanyInfo, unknown configure")
    
                
    def _setCompanyInfoByTable(self, req, res, table_class):
        '''
            对写配置的响应
            table_class 要操作的表对应的ORM类
        '''
        try:
            cmd = req.params['cmd']
            #过滤出要更新的表字段名和字段值
            exclude_fields = ['company_id','op_shop_id', 'username', 
                              'token', 'cmd', 'config_table', 'where_name', 
                              'where_value', 'sign']
            
            table_fields = {}
            for param in req.params['cmd'].keys():
                if param not in exclude_fields:
                    table_fields[param] = req.params[param]
                    
            company_id = req.params['company_id']
            table_class.doMapping(company_id)          
                  
            if cmd == 'add':
                #如果是对权限进行操作, 特殊处理
                if (table_class == UserRight):
                    return self._setUserRightsInfo(req, res, table_class)
                
                # 增加记录操作                
                table_object = table_class()
                for field in table_fields:
                    table_object.__setattr__(field, table_fields[field])
                    
                try:
                    self.dbsession.add(table_object)
                    self.dbsession.commit()
                except Exception, e:
                    CompanyService.log.e("CompanyService._setCompanyInfoByTable() add table %s failed" % table_object)                    
                    res.json = {'ret':-1, 'msg':'add failed'}
                    return                
                                               
                res.json = {"ret":0,"msg":"add ok"}
            elif cmd == 'update':
                #如果是对权限进行操作
                if (table_class == UserRight):
                    return self._setUserRightsInfo(req, res, table_class)
                
                #更新记录操作
                #获取要修改的表where字段
                where_name = req.params['where_name']
                where_value = req.params['where_value']
                #get the column attribute
                columnAttr = getattr(table_class, where_name)
                
                query_result = self.dbsession.query(table_class).filter(columnAttr == where_value)
                
                if query_result.count() == 0:                    
                    CompanyService.log.e("CompanyService._setCompanyInfoByTable(): no such record")
                    res.json = {'ret':-1, 'msg':'no such record'}
                    return
                
                for table_object in query_result:
                    for field in table_fields:
                        table_object.__setattr__(field, table_fields[field])
                        
                self.dbsession.commit()
                
                res.json = {'ret':0, 'msg' : 'update ok'}                
            elif cmd == 'del':                
                #删除记录操作
                
                where_name = req.params['where_name']
                where_value = req.params['where_value']
                #get the column attribute
                columnAttr = getattr(table_class, where_name)
                
                self.dbsession.query(table_class).filter(columnAttr == where_value).delete()
                self.dbsession.commit()
                                
                res.json = {'ret':0, 'msg' : 'delete ok'}
        except Exception, e:
            CompanyService.log.e('CompanyService:_setCompanyInfoByTable(): exception:%s' % e)
            res.json = {'ret':-1, 'msg': 'excetption'}
        
    def _setUserRightsInfo(self, req, res, table_class): 
        try:
            company_id = req.params['company_id']
            table_class.doMapping(company_id)                          
               
            user_id = req.params['user_id']                
            query_result = self.dbsession.query(table_class).filter(UserRight.user_id == user_id).all()
            for r in query_result:
                self.dbsession.delete(r)
                self.dbsession.commit()
                
            right_name = req.params['right_name']
            right_name = right_name[1:-1].split(',')
            for element in right_name:
                table_object = table_class()
                table_object.user_id=user_id
                table_object.right_name=element
                self.dbsession.add(table_object)
                self.dbsession.commit()
            
            res.json = {"ret":0,"msg":"ok"}
        except Exception, e:          
            CompanyService.log.e("CompanyService:_setCompanyInfoByTable exception： %s " % e)
            res.json = {"ret":-1,"msg":"exception"}
        